package com.pin.si.www.common.handler;

import com.pin.si.www.common.enums.GlobalHttpStateCodeConstants;
import com.pin.si.www.common.exception.ServiceException;
import com.pin.si.www.common.pojo.result.CommonResult;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        log.error("系统发生未捕获异常: {}", e.getMessage(), e);
        return CommonResult.failed(GlobalHttpStateCodeConstants.FAILED, e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public CommonResult<String> handleServiceException(ServiceException e) {
        log.warn("业务异常: 错误码={}, 错误信息={}", e.getErrorCode().getCode(), e.getErrorCode().getMsg(), e);
        return CommonResult.failed(e.getErrorCode());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<String> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));
        log.warn("参数校验失败: {}", message);
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, message);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<String> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = bindingResult.getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.warn("参数绑定异常: {}", message);
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, message);
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.warn("不支持的HTTP方法: {}", e.getMethod());
        return CommonResult.failed(GlobalHttpStateCodeConstants.METHOD_NOT_ALLOWED, e.getMessage());
    }
    
    /**
     * 处理资源未找到异常 (Spring 6.1+)
     */
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public CommonResult<String> handleNoResourceFoundException(NoResourceFoundException e) {
        log.warn("资源未找到: {} {}", e.getHttpMethod(), e.getResourcePath());
        return CommonResult.failed(GlobalHttpStateCodeConstants.NOT_FOUND, 
            String.format("请求的资源 %s 不存在", e.getResourcePath()));
    }

    /**
     * 处理方法参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String message = fieldErrors.stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.warn("方法参数校验失败: {}", message);
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, message);
    }

    /**
     * 处理请求参数缺失异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String message = String.format("缺少必要参数: %s", e.getParameterName());
        log.warn("请求参数缺失: 参数名={}, 参数类型={}", e.getParameterName(), e.getParameterType());
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, message);
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public CommonResult<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        String message = String.format("参数'%s'类型不匹配，期望类型: %s", e.getName(), Objects.requireNonNull(e.getRequiredType()).getSimpleName());
        log.warn("参数类型不匹配: 参数名={}, 实际值={}, 期望类型={}", 
                e.getName(), e.getValue(), e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "unknown");
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, message);
    }

    /**
     * 处理请求体不可读异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("请求体不可读: {}", e.getRootCause() != null ? e.getRootCause().getMessage() : e.getMessage(), e);
        return CommonResult.failed(GlobalHttpStateCodeConstants.VALIDATE_FAILED, 
                e.getRootCause() != null ? e.getRootCause().getMessage() : "请求体格式错误");
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public CommonResult<String> handleAccessDeniedException(AccessDeniedException e) {
        log.warn("权限不足: {}", e.getMessage(), e);
        return CommonResult.failed(GlobalHttpStateCodeConstants.FORBIDDEN);
    }

    /**
     * 处理404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public CommonResult<String> handleNoHandlerFoundException(NoHandlerFoundException e) {
        String errorMsg = String.format("请求地址 %s 不存在", e.getRequestURL());
        log.warn("404错误: 请求方法={}, 请求路径={}", e.getHttpMethod(), e.getRequestURL());
        return CommonResult.failed(GlobalHttpStateCodeConstants.NOT_FOUND, errorMsg);
    }

}
